package com.maoye.ossp.biz.contract.controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hotent.base.api.query.QueryFilter;
import com.hotent.base.api.query.QueryOP;
import com.maoye.ossp.biz.contract.entity.Assbrands;
import com.maoye.ossp.biz.contract.entity.AssociatedContract;
import com.maoye.ossp.biz.contract.entity.ContractRule;
import com.maoye.ossp.biz.contract.entity.ContractTemplate;
import com.maoye.ossp.biz.contract.service.RuleService;
import com.maoye.ossp.biz.contract.service.TemplateService;
import com.maoye.ossp.biz.contract.utils.CreateFilePDF;
import com.maoye.ossp.biz.contract.utils.PDFTool;
import com.maoye.ossp.biz.contract.utils.PdfGenerator.PdfGenerator;
import com.maoye.ossp.common.entity.Page;
import com.maoye.ossp.common.web.BaseController;
import com.maoye.ossp.sys.att.entity.Attachment;
import com.maoye.ossp.sys.att.service.IAttService;
import com.maoye.ossp.sys.base.utils.PropertyUtils;
import com.maoye.ossp.sys.org.util.UserUtils;
import com.maoye.ossp.sys.quartz.entity.SysQuartzLog;

/**
 * 合同模板管理
 * 
 * @author liuw
 * @data 2014年2月25日
 */
@Controller()
@RequestMapping(value = "biz/contract/template")
@SuppressWarnings("deprecation")
public class TemplateController extends BaseController {

	@Resource
	TemplateService service;

	@Resource
	RuleService ruleService;

	@Resource
	IAttService iattService;

	@RequestMapping(value = "getList")
	public String getList(HttpServletRequest request, HttpServletResponse response, Model model) {
		ContractTemplate template = new ContractTemplate();
		QueryFilter queryFilter = getQuerFilter(request,template);
		Page<ContractTemplate> page = service.find(queryFilter);
		model.addAttribute("page", page);
		model.addAttribute("list", page.getList());
//		Map<?, ?> map = new HashMap<Object, Object>();
//		List<ContractTemplate> list = service.getList(map);
//		model.addAttribute("list", list);
		return resultPage("/biz/template/list", model, request);
	}
	
	/**
	 * 添加或修改模板
	 * @author liuwei
	 */
	@RequestMapping(value = "addOrUpdate")
	public String addOrUpdate(ContractTemplate template, String jsonStr,
			Model model) {
		template.setTemplateContent(template.getTemplateContent().replace("&amp;#39;Times New Roman&amp;#39;", ""));	//在excel复制文字到模板的时候会出现'Times New Roman'， 在那里把它处理掉
		template.setTemplateContent(template.getTemplateContent().replace("&amp;#39;", ""));
		if (template.getId() != null) { // 添加或更新合同模板内容
			service.update(template);
		} else {
			if (template != null)
				template.setCreateTime(new Date());
			template.setCreateBy(UserUtils.getCurrentUserName());
			template.setId(idGenerator.getUId());
			service.add(template);
		}

		List<ContractRule> list = getListRule(jsonStr); // 添加或更新合同模板对象
		ruleService.del(template.getId());
		for (int i = 0; i < list.size(); i++) {
			ContractRule rule = list.get(i);
			rule.setId(idGenerator.getUId());
			rule.setTemplateId(template.getId());
			ruleService.add(rule);
		}
		return "redirect:getList";
	}

	/**
	 * 删除模板
	 */
	@RequestMapping(value = "del")
	public String del(HttpServletRequest request, HttpServletResponse response,
			Long id, Model model) {

		service.del(id); // 删除数据
		String path = request.getRealPath("")
				+ "/WEB-INF/views/biz/template/ftl/";
		File file = new File(path + id + ".ftl");
		if (file.isFile() && file.exists()) { // 删除文件
			file.delete();
		}
		return "redirect:getList";
	}

	/**
	 * 预览模板
	 */
	@RequestMapping(value = "preview")
	public String preview(Long id, Model model) {
		ContractTemplate template = service.getTemplate(id);
		String content = template.getTemplateContent();
		content = formatCharacter(content); // 处理特殊字符
		content = formatCharacter(content);
		model.addAttribute("content", content);
		return "preview.ftl";
	}
	
	/**
	 * 生成模板
	 */
	@RequestMapping(value = "create")
	@ResponseBody
	public String create(HttpServletRequest request,
			HttpServletResponse response, Long id, Model model) {

		//从配置文件中获得背景图片地址
		String imgPath = PropertyUtils.getContextProperty("ossp.pdf.background.image").toString();
		
		String pn = request.getRequestURI().split("/")[1];
		ContractTemplate template = service.getTemplate(id);
		String content = template.getTemplateContent();
		content = "<!DOCTYPE html><html>"
				+ "<head>"
				+ " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
				+ "<meta name=\"decorator\" content=\"sysDefault\" />"
				+ "<title>合同</title>"
				+ "<style type='text/css'>"
				
				+ "body{margin-left: 45px; margin-right: 45px;"
				+ "font-family: Arial Unicode MS;"
				+ "font-size: 10px;background-image: url(\""+imgPath+"\");"
				+ "background-attachment:fixed;}"

				+ ".txt{ color:black; "
				+ "border-bottom:1px solid black;"
				+ "border-top:0px; border-left:0px; "
				+ "border-right:0px; "
				+ "background-color:transparent; } </style>"

				+ "<script type='text/javascript'>"

				+ "function createPDF(obj){ var id=$('#id').val(); re = new RegExp(\",\", \"g\"); id=id.replace(re, \"\"); var url = window.location.href;"
				+ "post('/"+pn+"/biz/contract/template/formatPDF', {url:url, id:id});}"

				+ "function post(URL, PARAMS) {var temp = document.createElement(\"form\"); temp.action = URL;  "
				+ "temp.method = \"post\"; temp.style.display = \"none\"; for (var x in PARAMS) { "
				+ "var opt = document.createElement(\"textarea\");opt.name = x; opt.value = PARAMS[x];temp.appendChild(opt);}"
				+ "document.body.appendChild(temp); temp.submit(); return temp; }"

				+ "window.onload = function(){ $(\"input[type='text']\").each("
				+ "function(){ $(this).addClass('txt'); $(this).attr('readonly','readonly'); }); $('#buttonStr').removeAttr(\"style\") };"

				+ "$(document).ready(function(){ $(\"input[type='text']\").dblclick(function(){ $(this).removeAttr('readonly'); "
				+ "$(this).removeClass('txt'); }); });"

				+ "$(document).ready(function(){ $(\"input[type='text']\").blur(function(){"
				+ "$(this).attr('readonly','readonly');$(this).addClass('txt'); });});"

				+ "</script>"
				+ "</head><body><input type='button' id='buttonStr' value='生成PDF文件' onclick='createPDF()' style=\"display: none;\" /><input type='text' value='${id}' id='id' style=\"display: none;\"/>"
				+ content + "</body></html>";
		BufferedWriter writer = null;
		content=content.replace("mso-hansi-Times New Roman&quot;", "");
		content=content.replace("mso-ascii-font-family:&quot;", "");
		content=content.replace("new=&quot;&quot;", "");
		content=content.replace("times=&quot;&quot;", "");
		content=content.replace("roman&quot;,&quot;serif&quot;", "");
		content=content.replace("roman&quot;", "");
		content=content.replace("lfo1;&quot;", "");
		content=content.replace("lfo1;&quot;=&quot;&quot", "");
		content=content.replace("=&quot;&quot;", "");
		content=content.replace("roman&quot;,&quot;", "");
		content=content.replace("serif&quot;&quot;=&quot;&quot;", "");
		content=content.replace("font-family:&quot;", "");
		content=content.replace("font-family: KaiTi_GB2312;&quot;", "");
		content=content.replace("&quot; ;mso-ascii-;", "");
		
		content=content.replace("&quot;font-family: KaiTi_GB2312;&quot; &quot;", "&quot;&quot;");
		
		content = formatCharacter(content); // 处理特殊字符
		content = formatCharacter(content); // 处理特殊字符
		String path = CreateFilePDF.filePathFTL();		//获得ftl保存路径
		File file = new File(path);
		if(file != null && !file.exists()){
			file.mkdirs();						//创建ftl保存路径
		}

		try {
			writer = new BufferedWriter(new FileWriter(new File(path+"/"
					+ template.getId() + ".ftl")));
			writer.write(content);

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "";
	}

//	/**
//	 * 生成模板
//	 * @author liuwei
//	 */
//	@RequestMapping(value = "show")
//	public String show(Long id, Model model) {
//		return "testPdf.ftl";
//	}

	/**
	 * 显示模板编辑页面
	 */
	@RequestMapping(value = "showEditPage")
	public String showEditPage(Long id, Model model) {
		ContractTemplate template = service.getTemplate(id);
		if (template != null)
			template.setTemplateContent(formatCharacter(template
					.getTemplateContent()));
		model.addAttribute("template", template);
		return "/biz/template/edit";
	}

	/**
	 * 显示添加参数页面
	 */
	@RequestMapping(value = "showAddPage")
	public String showAddTemplatePage(ContractTemplate template, Model model) {
		List<ContractRule> list = null;
		if (template.getId() != null)
			list = ruleService.getList(template.getId());
		model.addAttribute("template", template);
		model.addAttribute("list", list);
		return "/biz/template/add";
	}

	/**
	 * 预览填充参数后的模板页面
	 */
	@RequestMapping(value = "showContract")
	public String showContract(Long id, Object obj, Model model,HttpServletRequest request) {
		obj = getAssoc();
		try {
			service.createPdf(id, "1", "test", obj, request);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return id + ".ftl";
	}

	/**
	 * HTML转换PDF
	 */
	@RequestMapping(value = "formatPDF")
	public String formatPDF(String url, Long id, HttpServletRequest request,
			Model model) {

		String pdfId = url.split("=")[1];
		String htmlName = url.split("=")[1] + ".html";
		String pdfName = System.currentTimeMillis() + ".pdf";
//		String pdfPath = request.getRealPath("")
//				+ "/WEB-INF/views/biz/template/pdf/" + pdfName;
		String pdfPath = CreateFilePDF.filePathPDF();
		String htmlPath = request.getRealPath("")
				+ "/WEB-INF/views/biz/template/ftl/" + htmlName;

		try {
			CreateFilePDF.createHtml(url, htmlPath, true); // 生成html
			PdfGenerator.createPDF(pdfPath, pdfName, htmlPath); // 生成pdf

			File file = new File(htmlPath); // 生成pdf后，删除html
			if (file.exists()) {
				file.delete();
			}

			Attachment att = new Attachment(); // 将pdf添加到附件管理中
			att.setId(idGenerator.getUId());
			att.setFileName(pdfName);
			att.setPath(pdfPath);
			att.setFileType("PDF");
			att.setServerName(pdfName);

		} catch (Exception ex) {
			System.err.println(" \n pdf生成失败");
			ex.printStackTrace();
		}
		return "redirect:showContract?id=" + pdfId;
	}

	/**
	 * 解析JSON字符串。返回List<ContractRule>对象
	 */
	public List<ContractRule> getListRule(String jsonStr) {
		List<ContractRule> list = new ArrayList<ContractRule>();
		ContractRule rule = null;
		JSONArray jsonArray = JSONArray.fromObject(jsonStr);

		if (jsonArray.size() > 0) {
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject json = (JSONObject) jsonArray.get(i);
				rule = new ContractRule();
				rule.setTemplateVariableName(json
						.getString("templateVariableName"));
				rule.setObjPropertyName(json.getString("objPropertyName"));
				rule.setObjPropertType(json.getString("objPropertType"));
				rule.setObjPropertFormat(json.getString("objPropertFormat"));
				list.add(rule);
			}
		}
		return list;
	}

	/**
	 * 特殊字符转换
	 */
	public String formatCharacter(String content) {
		content = content.replace("&lt;", "<");
		content = content.replace("&gt;", ">");
		content = content.replace("&amp;", "&");
		content = content.replace("&quot;", "\"");
		content = content.replace("&reg;", "®");
		content = content.replace("&copy;", "©");
		content = content.replace("&trade;", "™");
		content = content.replace("&yen", "¥");
		content = content.replace("&ldquo;", "“");
		content = content.replace("&rdquo;", "”");
		content = content.replace("&permil;", "%");
		content = content.replace("&#39;", "'");
		return content;
	}
	
	


	public AssociatedContract getAssoc() {
		AssociatedContract a = new AssociatedContract();
		a.setId(Long.parseLong("10000002531123"));
		a.setContractNo("A001"); // 一般对象
		a.setSignBy("liuwei");
		a.setSignBody("lingzhizhong");
		a.setContractStatus("失效");
		a.setContractAttribute("合同属性");
		a.setStartDate(new Date()); // 日期
		a.setCheckoutType("1"); // 字典

		Assbrands ass1 = new Assbrands(); // 集合对象
		ass1.setBrandNo("哇哈哈");
		Assbrands ass2 = new Assbrands();
		ass2.setBrandNo("蒙牛");
		Assbrands ass3 = new Assbrands();
		ass3.setBrandNo("怡宝");
		ArrayList<Assbrands> brandsList = new ArrayList<Assbrands>();
		brandsList.add(ass1);
		brandsList.add(ass2);
		brandsList.add(ass3);
		a.setAssbrandsList(brandsList);
		return a;
	}

	@RequestMapping(value = "test")
	public String test(Model model) {
		//PDFTool.genPdf("/opt/ossp/ftl/97590000000670189.html", "/opt/ossp/ftl/aaa.pdf");
		return SUCCESS;
	}
}
